package com.dwxt.community.aiequipment.sellmachine.service;

import com.dwxt.common.base.*;
import com.dwxt.common.util.*;
import com.dwxt.community.aiequipment.enumeration.*;
import com.dwxt.community.aiequipment.sellmachine.entity.*;
import com.dwxt.community.aiequipment.sellmachine.entity.enumeration.*;
import com.dwxt.community.aiequipment.sellmachine.entity.vo.SellMachineGoodsBuyRecordVo;
import com.dwxt.community.aiequipment.util.*;
import com.dwxt.community.dao.*;
import com.dwxt.community.entity.*;
import com.dwxt.community.exception.*;
import com.dwxt.community.service.*;
import com.dwxt.community.service.feign.*;
import com.github.pagehelper.*;
import org.apache.commons.lang3.*;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.*;

import javax.annotation.*;
import java.util.*;

/**
 * @author
 * @program: intelligentcity
 * @description: 售卖机服务层
 * @create: 2020/05/13
 */
@Service
public class SellMachineService {

    @Autowired
    private UserService userService;
    @Autowired
    private PayService payService;
    @Resource
    private SellMachineMapper sellMachineMapper;
    @Resource
    private SellMachineAisleMapper sellMachineAisleMapper;
    @Resource
    private SellMachineGoodsMapper sellMachineGoodsMapper;
    @Resource
    private SellMachineGoodsAddRecordMapper sellMachineGoodsAddRecordMapper;
    @Resource
    private SellMachineGoodsBuyRecordMapper sellMachineGoodsBuyRecordMapper;
    @Resource
    private SellMachineOrderMapper sellMachineOrderMapper;


    @Value("${cms.wx.wxCallback}")
    private String wxCallback;
    @Value("${cms.zfb.zfbCallback}")
    private String zfbCallback;

    private Logger logger = LoggerFactory.getLogger(SellMachineService.class);

    /**
     * 新增或者更新售卖机
     *
     * @param sellMachine
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult insertOrUpdate(SellMachine sellMachine) {
        String deviceId = sellMachine.getDeviceId();
        //设备编号
        String controlNo = sellMachine.getControlNo();
        int res;
        Date currDate = new Date();
        if (ObjectUtils.isEmpty(sellMachineMapper.selectByPrimaryKey(deviceId))) {
            /**
             * 新增
             */
            //判断设备编号不能重复
            if (judgeControlNoIsReDo(controlNo, null)) {
                throw new DefinedException(BaseResult.build(StatusCode.CONTROL_NO_IS_EXIST));
            }
            sellMachine.setCreateTime(currDate);
            sellMachine.setUpdateTime(currDate);
            res = sellMachineMapper.insertSelective(sellMachine);
        } else {
            /**
             * 更新
             */

            //判断设备编号不能重复
            if (judgeControlNoIsReDo(controlNo, deviceId)) {
                throw new DefinedException(BaseResult.build(StatusCode.CONTROL_NO_IS_EXIST));
            }
            sellMachine.setUpdateTime(currDate);
            res = sellMachineMapper.updateByPrimaryKeySelective(sellMachine);
        }
        return BaseResult.ok(res);
    }

    /**
     * @方法名：judgeControlNoIsReDo
     * @描述： 判断设备编号是否重复
     * @作者： kjz
     * @日期： Created in 2020/5/20 18:17
     */
    public boolean judgeControlNoIsReDo(String controlNo, String deviceId) {
        int controlNoCount = sellMachineMapper.selectCountByDeviceId(controlNo.trim(), deviceId);
        if (controlNoCount > 0) {
            return true;
        }
        return false;
    }

    /**
     * 售卖机 请求支付链接、查询支付状态、兑换
     *
     * @param sellMachineNetpay
     * @return
     */
    public int[] netPay(String ipAddr, SellMachineNetpay sellMachineNetpay) {
        int[] responseInts;
        switch (sellMachineNetpay.getNetPayType()) {
            //请求第三方支付链接
            case 0:
                responseInts = payHandler(ipAddr, sellMachineNetpay);
                return responseInts;

            //查询支付状态
            case 1:
                int payStatus = getPayStatus(sellMachineNetpay.getOrderCode());
                responseInts = ReplyBaseUtil.bulidBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), payStatus);
                return responseInts;

            //查询货道是否可以购买
            case 2:
                String deviceId = sellMachineNetpay.getDeviceId();
                Integer aisle = sellMachineNetpay.getAisle();
                List<SellMachineAisle> sellMachineAisles = sellMachineAisleMapper.selectAisleInfo(deviceId, aisle);
                responseInts = ReplyBaseUtil.bulidBaseResponseInts(16, 0, 0);
                if (ObjectUtils.isEmpty(sellMachineAisles)){
                    //15表示商品不足
                    responseInts[11] = 15;
                    return responseInts;
                }
                SellMachineAisle sellMachineAisle = sellMachineAisles.get(0);
                if (ObjectUtils.isEmpty(sellMachineAisle.getSellMachineGoods())||sellMachineAisle.getCurrentNum() < 1) {
                    //15表示商品不足
                    responseInts[11] = 15;
                    return responseInts;
                }
                //价格
                int price = (int) (sellMachineAisle.getSellMachineGoods().getGoodsPrice() * 10);
                responseInts[12] = DataHandler.low(price);
                responseInts[13] = DataHandler.high(price);
                return responseInts;

            //进行积分兑换
            case 3:
                responseInts = intergalConversion(sellMachineNetpay);
                return responseInts;

            default:
                responseInts = ReplyBaseUtil.bulidBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), ResStatueEnum.DATA_PARSE_ERROR.getCode());
                logger.info("售卖机支付接口类型不支持,收到 【{}】 仅支持【0，1，2，3】", sellMachineNetpay.getNetPayType());
                return responseInts;
        }
    }


    /**
     * 生成订单号、生成支付链接
     *
     * @return
     */
    private int[] payHandler(String ipAddr, SellMachineNetpay sellMachineNetpay) {
        switch (sellMachineNetpay.getPayType()) {
            case 1:
                //微信支付
                return pay(ipAddr, sellMachineNetpay);
            case 2:
                //支付宝支付
                return pay(ipAddr, sellMachineNetpay);

            default:
                //不支持的类型
                return ReplyBaseUtil.bulidBaseResponseInts(14, 0, 4);
        }
    }


    private int[] pay(String ipAddr, SellMachineNetpay sellMachineNetpay) {
        //订单ID
        String orderNo = IDUtils.genItemId();
        sellMachineNetpay.setOrderCode(orderNo);
        String payUrl = getPayUrl(ipAddr, sellMachineNetpay);
        if (StringUtils.isEmpty(payUrl)) {
            return ReplyBaseUtil.bulidBaseResponseInts(14, 0, 11);
        }
        //将付款链接和订单号写入回复数组
        int[] responseInts = ReplyBaseUtil.bulidBaseResponseInts(33 + payUrl.length() + 2, ResStatueEnum.OK.getCode(), ResStatueEnum.OK.getCode());
        char[] orderNoInts = orderNo.toCharArray();
        char[] urlInts = payUrl.toCharArray();
        int offset;
        for (offset = 0; offset < orderNoInts.length; offset++) {
            responseInts[12 + offset] = orderNoInts[offset];
        }
        // responseInts[12 + orderNoInts.length] = urlInts.length;
        responseInts[32] = urlInts.length;
        logger.info("支付链接长度所在位置{}，以及长度值{},char数组{},string内容{},string长度", 32, urlInts.length, Arrays.toString(payUrl.toCharArray()), payUrl, payUrl.length());
        for (offset = 0; offset < urlInts.length; offset++) {
            responseInts[33 + offset] = urlInts[offset];
        }
        return responseInts;
    }

    private String getPayUrl(String ipAddr, SellMachineNetpay sellMachineNetpay) {
        String payUrl = null;
        BaseResult baseResult;
        //验证商品合法
        List<SellMachineAisle> sellMachineAisles = sellMachineAisleMapper.selectAisleInfo(sellMachineNetpay.getDeviceId(), sellMachineNetpay.getAisle());
        if (ObjectUtils.isEmpty(sellMachineAisles)) {
            return payUrl;
        }
        //订单对象
        SellMachineOrder sellMachineOrder = new SellMachineOrder();
        Date currDate = new Date();
        String orderId = sellMachineNetpay.getOrderCode();
        //按支付类型请求支付链接
        Integer payType = sellMachineNetpay.getPayType();
        HashMap<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("price", String.valueOf(sellMachineAisles.get(0).getSellMachineGoods().getGoodsPrice()));
        map.put("type", String.valueOf(2));
        if (payType.equals(PayTypeEnum.ALI_PAY.getCode())) {
            map.put("notifyUrl", zfbCallback);
            baseResult = payService.getAliPayInfo(map);
            LinkedHashMap<String, String> alipayResMap = ((LinkedHashMap<String, LinkedHashMap<String, String>>) baseResult.getData()).get("alipay_trade_precreate_response");
            if ("Success".equals(alipayResMap.get("msg"))) {
                payUrl = alipayResMap.get("qr_code");
            }
        } else if (payType.equals(PayTypeEnum.WECHAT_PAY.getCode())) {
            map.put("notifyUrl", wxCallback);
            map.put("ip", ipAddr);
            baseResult = payService.getWxPayInfo(map);
            payUrl = ((LinkedHashMap<String, String>) baseResult.getData()).get("codeUrl");
        }

        //生成待支付订单
        sellMachineOrder.setPayType(payType);
        sellMachineOrder.setOrderPrice(sellMachineAisles.get(0).getSellMachineGoods().getGoodsPrice());
        sellMachineOrder.setOrderId(orderId);
        sellMachineOrder.setOrderStatus(YesOrNo.NO);
        sellMachineOrder.setCreateTime(currDate);
        sellMachineOrder.setGoodsId(sellMachineAisles.get(0).getSellMachineGoods().getGoodsId());
        sellMachineOrder.setSellMachineId(sellMachineNetpay.getDeviceId());
        sellMachineOrder.setUpdateTime(currDate);
        sellMachineOrder.setAisleNo(sellMachineNetpay.getAisle());
        sellMachineOrderMapper.insert(sellMachineOrder);

        return payUrl;
    }

    /**
     * 获取支付状态
     *
     * @return
     */
    private int getPayStatus(String orderId) {
        int status = 0;
        SellMachineOrder sellMachineOrder = sellMachineOrderMapper.selectByPrimaryKey(orderId);
        if (sellMachineOrder == null) {
            return 10;
        } else if (!sellMachineOrder.getOrderStatus().equals(YesOrNo.YES)) {
            if (PayTypeEnum.WECHAT_PAY.getCode().equals(sellMachineOrder.getPayType())) {
                status = modifySellMachineOrderStatus(payService.getWxPayStatus(orderId).getStatus(), sellMachineOrder);
            } else if (PayTypeEnum.ALI_PAY.getCode().equals(sellMachineOrder.getPayType())) {
                status = modifySellMachineOrderStatus(payService.getZfbPayStatus(orderId).getStatus(), sellMachineOrder);
            } else {
                status = sellMachineOrder.getOrderStatus();
            }
        } else {
            status = sellMachineOrder.getOrderStatus();
        }
        return status == 1 ? 0 : 10;
    }

    @Transactional(rollbackFor = Exception.class)
    public int modifySellMachineOrderStatus(Integer code, SellMachineOrder sellMachineOrder) {
        if (code == 200) {
            SellMachineOrder smo = sellMachineOrderMapper.selectByPrimaryKey(sellMachineOrder.getOrderId());
            smo.setOrderStatus(YesOrNo.YES);
            return sellMachineOrderMapper.updateByPrimaryKeySelective(smo);
        } else {
            return YesOrNo.NO;
        }
    }

    /**
     * 积分兑换
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int[] intergalConversion(SellMachineNetpay sellMachineNetpay) {
        String cardNo = sellMachineNetpay.getCardNo();
        Integer aisle = sellMachineNetpay.getAisle();
        //用户信息
        User user = userService.selectUserByPrimaryKey(cardNo);
        if (user == null) {
            //卡号未注册
            return ReplyBaseUtil.bulidBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), ResStatueEnum.CODE_NOT_REGISTER.getCode());
        }
        //货道信息
        List<SellMachineAisle> sellMachineAisles = sellMachineAisleMapper.selectAisleInfo(sellMachineNetpay.getDeviceId(), aisle);
        if (ObjectUtils.isEmpty(sellMachineAisles)) {
            //货道信息异常
            return ReplyBaseUtil.bulidBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), ResStatueEnum.NOT_GOODS.getCode());
        }
        SellMachineAisle sellMachineAisle = sellMachineAisles.get(0);
        if (ObjectUtils.isEmpty(sellMachineAisle.getSellMachineGoods())||sellMachineAisle.getCurrentNum()<=sellMachineAisle.getAisleMin()) {
            //货道未配置商品或者商品不足异常
            return ReplyBaseUtil.bulidBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), ResStatueEnum.WANT_GOODS.getCode());
        }
        if (sellMachineAisle.getSellMachineGoods().getGoodsPrice() * 1000 > user.getIntegral()) {
            //积分不足以支付
            return ReplyBaseUtil.bulidBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), ResStatueEnum.QRCODE_PAY_FAILED.getCode());
        }
        //扣除积分
        userService.updateIntegral(-(int) (sellMachineAisle.getSellMachineGoods().getGoodsPrice() * 1000), null, "礼品机兑换" + sellMachineAisle.getSellMachineGoods().getGoodsName(), cardNo);
        //扣除当前货架上的数
        sellMachineAisle.setCurrentNum(sellMachineAisle.getCurrentNum() - 1);
        sellMachineAisleMapper.updateByPrimaryKeySelective(sellMachineAisle);
        //添加支付订单
        String orderId = IDUtils.genItemId();
        Date currDate = new Date();
        SellMachineOrder sellMachineOrder = new SellMachineOrder();
        sellMachineOrder.setPayType(sellMachineNetpay.getPayType());
        sellMachineOrder.setOrderPrice(sellMachineAisles.get(0).getSellMachineGoods().getGoodsPrice());
        sellMachineOrder.setOrderId(orderId);
        sellMachineOrder.setOrderStatus(YesOrNo.YES);
        sellMachineOrder.setCreateTime(currDate);
        sellMachineOrder.setGoodsId(sellMachineAisles.get(0).getSellMachineGoods().getGoodsId());
        sellMachineOrder.setSellMachineId(sellMachineNetpay.getDeviceId());
        sellMachineOrder.setUpdateTime(currDate);
        sellMachineOrder.setAisleNo(sellMachineNetpay.getAisle());
        sellMachineOrderMapper.insert(sellMachineOrder);
        //添加购买记录
        SellMachineGoodsBuyRecord smbgr = new SellMachineGoodsBuyRecord();
        smbgr.setGoodsPrice(sellMachineAisles.get(0).getSellMachineGoods().getGoodsPrice());
        smbgr.setRecordCreateTime(currDate);
        smbgr.setRecordUpdateTime(currDate);
        smbgr.setGoodsId(sellMachineAisles.get(0).getSellMachineGoods().getGoodsId());
        smbgr.setOrderId(orderId);
        smbgr.setDeviceId(sellMachineNetpay.getDeviceId());
        smbgr.setAisleNo(sellMachineNetpay.getAisle());
        smbgr.setRecordId(IDUtils.genItemId());
        smbgr.setBuyerId(cardNo);
        sellMachineGoodsBuyRecordMapper.insertSelective(smbgr);
        //返回结果
        return ReplyBaseUtil.bulidBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), ResStatueEnum.OK.getCode());
    }

    /**
     * @param sellMachineNetpay
     * @return
     */
    public int[] newReceive(SellMachineNetpay sellMachineNetpay) {
        switch (sellMachineNetpay.getNetPayType()) {
            case 0:
                //兑换机验证兑换资格
                return verifyCard(sellMachineNetpay);
            case 1:
                //袋子机验证领取资格
                return verifyZiGe(sellMachineNetpay);

            default:
                //不支持类型，返回数据解析异常
                return ReplyBaseUtil.bulidBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), ResStatueEnum.DATA_PARSE_ERROR.getCode());
        }
    }

    /**
     * 验证兑换资格
     *
     * @param sellMachineNetpay
     * @return
     */
    private int[] verifyCard(SellMachineNetpay sellMachineNetpay) {
        User user = userService.selectUserByPrimaryKey(sellMachineNetpay.getCardNo());
        int[] responseInts = ReplyBaseUtil.bulidBaseResponseInts(50, ResStatueEnum.OK.getCode(), ResStatueEnum.OK.getCode());
        //默认不可以领取
        responseInts[12] = 1;
        if (ObjectUtils.isEmpty(user)) {
            //13表示未注册
            responseInts[11] = 13;
            responseInts[13] = 1;
            return responseInts;
        }
        //积分数值
        int score = user.getIntegral();
        int[] bili;
        if (score <= 0) {
            bili = DataHandler.splitLong2FourLowHigh(0L);
            responseInts[18] = bili[0];
            responseInts[19] = bili[1];
            responseInts[20] = bili[2];
            responseInts[21] = bili[3];
        } else {
            bili = DataHandler.splitLong2FourLowHigh((long) score);
            responseInts[18] = bili[0];
            responseInts[19] = bili[1];
            responseInts[20] = bili[2];
            responseInts[21] = bili[3];
        }
        //兑换比例
        responseInts[22] = DataHandler.low(1000);
        responseInts[23] = DataHandler.high(1000);
        //设置掉货的货道
        //查询可用货道
        List<SellMachineAisle> goodsWayCodeList = sellMachineAisleMapper.selectUsableAisle(sellMachineNetpay.getDeviceId());
        if (ObjectUtils.isNotEmpty(goodsWayCodeList)) {
            int resIntsSize;
            for (resIntsSize = 0; resIntsSize < goodsWayCodeList.size(); ++resIntsSize) {
                responseInts[resIntsSize * 3 + 24] = 1;
                responseInts[resIntsSize * 3 + 25] = DataHandler.low(goodsWayCodeList.get(resIntsSize).getAisleNo());
                responseInts[resIntsSize * 3 + 26] = DataHandler.high(goodsWayCodeList.get(resIntsSize).getAisleNo());
            }
        } else {
            //没有可用货道不能兑换
            responseInts[12] = 1;
            responseInts[13] = 1;
        }
        return responseInts;
    }

    /**
     * 验证领取资格 默认不能领取
     *
     * @param sellMachineNetpay
     * @return
     */
    private int[] verifyZiGe(SellMachineNetpay sellMachineNetpay) {
        User user = userService.selectUserByPrimaryKey(sellMachineNetpay.getCardNo());
        int[] responseInts = ReplyBaseUtil.bulidBaseResponseInts(50, ResStatueEnum.OK.getCode(), ResStatueEnum.OK.getCode());
        //默认不能领取
        responseInts[12] = 1;
        //默认积分不足
        responseInts[13] = 1;
        if (ObjectUtils.isEmpty(user)) {
            //13表示未注册
            responseInts[11] = 13;
        }
        return responseInts;
    }



    /**
     * 售卖机列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo get(Integer pageNum, Integer pageSize,String controlNo,Integer using) {
        PageHelper.startPage(pageNum, pageSize);
        List<SellMachine> sellMachineList = sellMachineMapper.selectAll(controlNo,using);
        //得到货道数量
        sellMachineList.forEach(sellMachine -> {
            Integer aisleNumber = sellMachineAisleMapper.countByDeviceId(sellMachine.getDeviceId());
            sellMachine.setAisleNumber(aisleNumber);
        });
        return new PageInfo<>(sellMachineList);
    }

    /**
     * 售卖机详情
     *
     * @param id
     * @return
     */
    public SellMachine detail(String id) {
        return sellMachineMapper.selectMachineAisleByPrimaryKey(id);
    }


    /**
     * 售卖机停用或者启用
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult useOrStop(String id) {
        SellMachine sellMachine = sellMachineMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(sellMachine)) {
            return BaseResult.build(StatusCode.SELL_MACHINE_NOT_EXIST);
        }
        Integer useing = sellMachine.getUseing();
        if (useing == null) {
            sellMachine.setUseing(YesOrNo.YES);
        } else if (YesOrNo.YES == useing) {
            sellMachine.setUseing(YesOrNo.NO);
        } else {
            sellMachine.setUseing(YesOrNo.YES);
        }
        sellMachineMapper.updateByPrimaryKeySelective(sellMachine);
        return BaseResult.ok();
    }


/************************************************/
/*       货道
/************************************************/
    @Transactional(rollbackFor = Exception.class)
    public int aisleInsertOrUpdate(SellMachineAisle sellMachineAisle) {
        String aisleId = sellMachineAisle.getAisleId();

        //兑换机id
        String machineId = sellMachineAisle.getMachineId();
        //货道编号
        Integer aisleNo = sellMachineAisle.getAisleNo();

        int res;
        if (StringUtils.isBlank(aisleId)) {
            /**
             * 新增
             */

            //判断货道编号不能重复
            if (judgeAisleNoIsReDo(machineId, aisleNo, null)) {
                throw new DefinedException(BaseResult.build(StatusCode.AISLENO_IS_EXIST));
            }
            sellMachineAisle.setAisleId(IDUtils.genItemId());
            res = sellMachineAisleMapper.insert(sellMachineAisle);
        } else {
            /**
             * 修改
             */
            //修改商品时要判断当前商品库存，如果大于0不允许修改商品
            Integer currentNum = sellMachineAisle.getCurrentNum();
            String aisleGoodsId = sellMachineAisle.getAisleGoodsId();
            SellMachineAisle oldAisle = this.sellMachineAisleMapper.selectByPrimaryKey(aisleId);
            String oldAisleGoodsId = oldAisle.getAisleGoodsId();
            if(oldAisleGoodsId!=null && !oldAisleGoodsId.equals(aisleGoodsId)){
                if(currentNum>0){
                    throw new DefinedException(BaseResult.build(StatusCode.CURRENTNUM_MUST_BE_CLEARED));
                }
            }
            //判断货道编号不能重复
            if (judgeAisleNoIsReDo(machineId, aisleNo, aisleId)) {
                throw new DefinedException(BaseResult.build(StatusCode.AISLENO_IS_EXIST));
            }
            res = sellMachineAisleMapper.updateByPrimaryKeySelective(sellMachineAisle);
        }
        return res;
    }

    /**
     * @方法名：judgeAisleNoIsReDo
     * @描述： 判断同一兑换机的货道号是否重复
     * @作者： kjz
     * @日期： Created in 2020/5/20 17:32
     */
    public boolean judgeAisleNoIsReDo(String machineId, Integer aisleNo, String aisleId) {
        int aisleNoCount = sellMachineAisleMapper.selectAisleNoCountByMachineId(machineId, aisleNo, aisleId);
        if (aisleNoCount > 0) {
            return true;
        }
        return false;
    }


/************************************************/
/*       商品
/************************************************/

    /**
     * 售卖机商品添加修改
     *
     * @param sellMachineGoods
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int goodsInsertOrUpdate(SellMachineGoods sellMachineGoods) {
        String goodsId = sellMachineGoods.getGoodsId();
        Date currDate = new Date();
        //商品名
        String goodsName = sellMachineGoods.getGoodsName();
        int res;
        if (StringUtils.isBlank(goodsId)) {
            /**
             * 新增
             */
            sellMachineGoods.setGoodsId(IDUtils.genItemId());
            sellMachineGoods.setGoodsCreateTime(currDate);
            sellMachineGoods.setGoodsUpdateTime(currDate);

            //判断商品名不能重复
            if (judgeGoodsNameExist(goodsName, null)) {
                throw new DefinedException(BaseResult.build(StatusCode.GOODS_NAME_IS_EXIST));
            }
            res = sellMachineGoodsMapper.insert(sellMachineGoods);
        } else {
            /**
             * 修改
             */

            //判断商品名不能重复
            if (judgeGoodsNameExist(goodsName, goodsId)) {
                throw new DefinedException(BaseResult.build(StatusCode.GOODS_NAME_IS_EXIST));
            }
            sellMachineGoods.setGoodsUpdateTime(currDate);
            res = sellMachineGoodsMapper.updateByPrimaryKeySelective(sellMachineGoods);
        }
        return res;
    }

    /**
     * @方法名：judgeGoodsNameExist
     * @描述： 判断商品名是否重复
     * @作者： kjz
     * @日期： Created in 2020/5/20 17:48
     */
    public boolean judgeGoodsNameExist(String goodsName, String goodsId) {
        int goodsCount = sellMachineGoodsMapper.selectGoodsCountByGoodsName(goodsName.trim(), goodsId);
        if (goodsCount > 0) {
            return true;
        }
        return false;
    }

    /**
     * 商品停用启用
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult goodsUseOrStop(String id) {
        SellMachineGoods sellMachineGoods = sellMachineGoodsMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(sellMachineGoods)) {
            return BaseResult.build(StatusCode.GOODS_NOT_EXIST);
        }
        Integer useing = sellMachineGoods.getGoodsUseing();
        if (useing == null) {
            sellMachineGoods.setGoodsUseing(YesOrNo.YES);
        } else if (YesOrNo.YES == useing) {
            //查询判断商品是否已经绑定兑换机货道
            if (judgeGoodsIsExistAisle(id)) {
                return BaseResult.build(StatusCode.GOODS_HAVE_LINKED_TO_AISLE);
            }
            sellMachineGoods.setGoodsUseing(YesOrNo.NO);
        } else {
            sellMachineGoods.setGoodsUseing(YesOrNo.YES);
        }
        sellMachineGoodsMapper.updateByPrimaryKeySelective(sellMachineGoods);
        return BaseResult.ok();
    }

    /**
     * @方法名：judgeGoodsIsExistAisle
     * @描述： 判断商品是否已经在货道中存在(已经绑定货道)
     * @作者： kjz
     * @日期： Created in 2020/5/20 15:56
     */
    public boolean judgeGoodsIsExistAisle(String goodsId) {
        //统计商品在货道中的数量(暂时没有考虑兑换机停用,因为考虑停用兑换机，那也存在兑换机重新启用的情况)
        int goodsCount = sellMachineAisleMapper.countByAisleGoodsId(goodsId);
        if (goodsCount > 0) {
            return true;
        }
        return false;
    }

    /**
     * 商品列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo goodsGet(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo(sellMachineGoodsMapper.selectAll());
    }

    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    public SellMachineGoods goodsDetail(String id) {
        return sellMachineGoodsMapper.selectByPrimaryKey(id);
    }

    /**
     * 获取售卖机下的商品
     *
     * @param no
     * @return
     */
    public BaseResult getGoodsBySellMachineId(String no) {
        SellMachine sellMachines = sellMachineMapper.selectMachineAisleByDeviceNo(no);
        if (ObjectUtils.isEmpty(sellMachines)) {
            if (ObjectUtils.isEmpty(sellMachineMapper.selectByDeviceNo(no))) {
                return BaseResult.build(StatusCode.SELL_MACHINE_NOT_EXIST);
            }
            return BaseResult.build(StatusCode.SELL_MACHINE_AISLE_ERROR);
        }
        return BaseResult.ok(sellMachines);
    }

    /**
     * 补货
     *
     * @param sellMachineAisleDTOs
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult replenishment(List<SellMachineAisle> sellMachineAisleDTOs) {
        Date currDate = new Date();
        for (SellMachineAisle sellMachineAisleDto : sellMachineAisleDTOs) {
            //补货后数量
            Integer numed = sellMachineAisleDto.getCurrentNum();
            SellMachineAisle sellMachineAisle = sellMachineAisleMapper.selectAisleInfo(sellMachineAisleDto.getMachineId(), sellMachineAisleDto.getAisleNo()).get(0);
            if (!numed.equals(sellMachineAisle.getCurrentNum())) {
                //补存的数量
                int num =  numed - sellMachineAisle.getCurrentNum();
                //判断补货是否合法
                if (numed > sellMachineAisle.getAisleMax() || numed <0) {
                    return BaseResult.build(StatusCode.GOODS_NUM_ERROR);
                }

                //添加补货记录
                SellMachineGoodsAddRecord sellMachineGoodsAddRecord = new SellMachineGoodsAddRecord();
                sellMachineGoodsAddRecord.setAddNumm(num);
                sellMachineGoodsAddRecord.setAddAgoNum(numed);
                sellMachineGoodsAddRecord.setAisleNo(sellMachineAisleDto.getAisleNo());
                sellMachineGoodsAddRecord.setCreateTime(currDate);
                sellMachineGoodsAddRecord.setUpdateTime(currDate);
                sellMachineGoodsAddRecord.setRecordId(IDUtils.genItemId());
                sellMachineGoodsAddRecord.setDeviceId(sellMachineAisleDto.getMachineId());
                sellMachineGoodsAddRecord.setOperationId(PartyUtil.getCurrentUserId());
                sellMachineGoodsAddRecordMapper.insert(sellMachineGoodsAddRecord);

                //修改当前数量
                sellMachineAisle.setCurrentNum(sellMachineAisle.getCurrentNum()+num);
                sellMachineAisle.setAisleUpdateTime(currDate);
                sellMachineAisleMapper.updateByPrimaryKeySelective(sellMachineAisle);
            }

        }
        return BaseResult.ok();
    }

    /**
     * 商品销售记录
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo goodsSellRecord(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo(sellMachineGoodsBuyRecordMapper.selectAll());
    }

    /**
     * 获取所有货道
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo aisleGet(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo(sellMachineAisleMapper.selectAll());
    }

    /**
     * 根据兑换机id查询货道列表
     *
     * @param pageNum
     * @param pageSize
     * @param machineId
     * @return
     */
    public PageInfo getAisleByMachineId(Integer pageNum, Integer pageSize, String machineId) {
        PageHelper.startPage(pageNum, pageSize);
        List<SellMachineAisle> list = sellMachineAisleMapper.selectAisleByMachineId(machineId);
        PageInfo<SellMachineAisle> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 根据货道id查询货道详情
     *
     * @param aisleId
     * @return
     */
    public SellMachineAisle sellMachineAisleDetail(String aisleId) {
        return sellMachineAisleMapper.sellMachineAisleDetail(aisleId);
    }


    /**
     * @方法名：goodsAllGet
     * @描述： 获取所有商品列表(不带分页)
     * @作者： kjz
     * @日期： Created in 2020/5/20 16:19
     */
    public List<SellMachineGoods> goodsAllGet() {
        return sellMachineGoodsMapper.selectSellMachineGoodsByUseing();
    }

    /**
     * 据货道id清空货道的商品
     *
     * @param aisleId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int emptyGoodsByAisleId(String aisleId) {
        return sellMachineAisleMapper.emptyGoodsByAisleId(aisleId);
    }


    public SellMachine selectByPrimaryKey(String deviceId) {
        return sellMachineMapper.selectByPrimaryKey(deviceId);
    }

    /**
     * 售卖机握手设备注册
     *
     * @param sellMachine
     */
    public int wsInsertOrUpdate(SellMachine sellMachine) {
        SellMachine sm = sellMachineMapper.selectByPrimaryKey(sellMachine.getDeviceId());
        Date currDate = new Date();
        if (ObjectUtils.isEmpty(sm)) {
            //注册设备
            sellMachine.setCreateTime(currDate);
            sellMachine.setUpdateTime(currDate);
            //默认启用
            sellMachine.setUseing(YesOrNo.YES);
            sellMachineMapper.insertSelective(sellMachine);
            //添加货道
           return addAisle(sellMachine.getDeviceId());
        } else {
            List<SellMachineAisle> sellMachineAisles = sellMachineAisleMapper.selectAisleByMachineId(sellMachine.getDeviceId());
            if (ObjectUtils.isEmpty(sellMachineAisles)){
                addAisle(sellMachine.getDeviceId());
            }
            sellMachine.setUpdateTime(currDate);
            return sellMachineMapper.updateByPrimaryKeySelective(sellMachine);
        }
    }

    public int addAisle(String deviceId){
        Date currDate = new Date();
        ArrayList<SellMachineAisle> sellMachineAisles = new ArrayList<>();
        //每台设备有69个货道
        for (int i = 0; i < 69; i++) {
            SellMachineAisle sellMachineAisle = new SellMachineAisle();
            sellMachineAisle.setCurrentNum(0);
            sellMachineAisle.setMachineId(deviceId);
            sellMachineAisle.setAisleCreateTime(currDate);
            sellMachineAisle.setAisleId(UUID.randomUUID().toString());
            sellMachineAisle.setAisleNo(i+1);
            sellMachineAisle.setAisleUpdateTime(currDate);
            sellMachineAisle.setAisleUseing(YesOrNo.YES);
            sellMachineAisle.setAisleMin(0);
            //这几个货道无效
            if (i == 61 || i == 63 || i == 65 || i == 67) {
                continue;
            }
            int aisle = i / 10;
            if (aisle == 4 || aisle == 5) {
                sellMachineAisle.setAisleMax(5);
            } else if (aisle == 6) {
                sellMachineAisle.setAisleMax(3);
            } else if (aisle == 3 || aisle == 2) {
                sellMachineAisle.setAisleMax(7);
            } else {
                sellMachineAisle.setAisleMax(11);
            }
            sellMachineAisles.add(sellMachineAisle);
        }
        return sellMachineAisleMapper.batchInsert(sellMachineAisles);
    }

    /**
     * 礼品兑换次数查询
     */
    public BaseResult selectGiftExchangeTimes() {
        List<SellMachineGoodsBuyRecordVo> sellMachineGoodsBuyRecordVos = sellMachineGoodsBuyRecordMapper.selectGiftExchangeTimes();
        return BaseResult.ok(sellMachineGoodsBuyRecordVos);
    }

}
